package lambdasinaction.chap1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * chapter1
 *
 * @author Fish
 * @since 0.0.1 2018/7/15 16:21
 */
public class MyFilteringApples {

  public static void main(String[] args) {
    List<Apple> inventory = Arrays.asList(new Apple("red", 80),
        new Apple("green", 155),
        new Apple("red", 120));

    // 传统方法
    // 得到所有的绿苹果
//    System.out.println(filterGreenApples(inventory));

    // 得到所有重量大于150克的苹果
//    System.out.println(filterHeavyApples(inventory));

    // 使用方法引用，就是替代那些转发参数的 Lambda 表达式的语法糖。 使代码更简洁
//    List<Apple> greenApples = filter(inventory, MyFilteringApples::isGreenApple);
//    System.out.println(greenApples);

//    List<Apple> heavyApples = filter(inventory, MyFilteringApples::isHeavyApple);
//    System.out.println(heavyApples);

//    List<Apple> greenApples2 = filter(inventory, (Apple a) -> a.getColor().equals("green"));
//    System.out.println(greenApples2);
//    List<Apple> heavyApples2 = filter(inventory, (Apple a) -> a.getWeight() > 150);
//    System.out.println(heavyApples2);
//    List<Apple> weridApples = filter(inventory, (Apple a) -> a.getWeight() < 80 ||
//      a.getColor().equals("browb"));
//    System.out.println(weridApples);

  }

  public static boolean isHeavyApple(Apple apple) {
    return apple.getWeight() > 150;
  }

  public static boolean isGreenApple(Apple apple) {
    return apple.getColor().equals("green");
  }

  public static List<Apple> filter(List<Apple> inventory, Predicate<Apple> predicate) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
      if (predicate.test(apple)) {
        result.add(apple);
      }
    }
    return result;
  }

  public static List<Apple> filterHeavyApples(List<Apple> inventory) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
      if (apple.getWeight() > 150) {
        result.add(apple);
      }
    }
    return result;
  }

  public static List<Apple> filterGreenApples(List<Apple> inventory) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
      if (apple.getColor().equals("green")) {
        result.add(apple);
      }
    }
    return result;
  }


  public static class Apple {

    private String color;
    private Integer weight;

    public Apple(String color, Integer weight) {
      this.color = color;
      this.weight = weight;
    }

    public String getColor() {
      return color;
    }

    public void setColor(String color) {
      this.color = color;
    }

    public Integer getWeight() {
      return weight;
    }

    public void setWeight(Integer weight) {
      this.weight = weight;
    }

    @Override
    public String toString() {
      return "Apple{" +
          "color='" + color + '\'' +
          ", weight=" + weight +
          '}';
    }
  }

}
